﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eCRAM.WebSite.Models;
using eCRAM.Model;
using eCRAM.Dao;
using eCRAM.Bll;
using eCRAM.UIElement;
using System.Globalization;
using Microsoft.Practices.Unity;
using eCRAM.Tools;
using System.Configuration;
using System.Web.Security;

namespace eCRAM.WebSite.Controllers
{
    [HandleError]
    public class CramController : Controller
    {
         //Account controller has a dependency with  HttpSessionStateBase (base class not instance)
        ISession _session = null;

        //Cram controller has a dependency with IRepository (interface not instance)
        private ICramManager CramManager = null;


        private IActivityManager ActivityManager = null;

        //Account controller has a dependency with IRepository (interface not instance)
        public IUserManager UserManage = null;

        //Constructor
        //..
        /// <summary>
		/// class Constructor
		/// Inject instance of ActivityRepository using construction injection
		/// </summary>
		/// <param name="formsAuth"></param>
		/// <param name="service"></param>
        public CramController(ISession session, IActivityManager activityManager, ICramManager cramRepo,IUserManager userManager)
		{
			CramManager = cramRepo;
			_session = session;
            ActivityManager = activityManager;
            UserManage = userManager;
		}


        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (this.Session["MySessionData"] == null && FormsAuthentication.FormsCookieName != null && 
                Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    User user =UserManage.GetUser(FormsAuthentication.Decrypt(cookie.Value).Name);

                    //FIXME
                    SessionData session = new SessionData
                    {
                        CurrentUser = user
                    };

                    _session["MySessionData"] = session;
                }
            }
        }

        [AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public ActionResult CramList()
        {
            if (((SessionData)Session["MySessionData"]).CurrentCram == null)
            {
                return Add(DateTime.Now.Month, DateTime.Now.Year);
            }
            else
            {
                return ViewCram();
            }
            //return View();
        }

        public ActionResult Index()
        {
            return View();
        }

         [Authorize]
        public ActionResult GiveCram(string monthName, string year)
        {
           
             return Add((monthName == String.Empty) ? DateTime.Now.Month : int.Parse(monthName),
                      (year == String.Empty) ? DateTime.Now.Year : int.Parse(year));

        }

         [Authorize]
        public ActionResult Add(int month,int year)
        {
            Guid userId=((SessionData)Session["MySessionData"]).CurrentUser.Id;
            Cram cram = CramManager.FindCram(userId, month, year);
            if (cram==null)
            {
                 cram = CreateCram(month,year);
                
            }

            ((SessionData)Session["MySessionData"]).CurrentCram = cram;
            return ViewCram();
        }

         [Authorize]
        public ActionResult ViewCram()
        {
            Cram cram = ((SessionData)Session["MySessionData"]).CurrentCram;
            PageData mod = new PageData()
            {
                Cram = cram,
                GridViewData = new GridViewData<CramLine>
                {
                    PagedList = cram.CramLines.ToList().ToPagedList<CramLine>(),
                   // EditItem = _currentCram.CramLines.Where(e => e.Id == id).Single()
                }
            };
            ViewData["activityEnum"] = GetListActivity();
            ViewData["monthEnum"] = GetListMonth();
            ViewData["yearEnum"]=GetYearList();

            return View("CramDetails", mod);
        }

        
        private List<SelectListItem> GetYearList()
        {
            List<SelectListItem> YearEnums = new List<SelectListItem>();
            int currentYear = DateTime.Now.Year;
            for (int j = currentYear - yearMeans; j <= currentYear + yearMeans; j++)
            {
                var item = new SelectListItem();
                item.Value = Convert.ToString(j);
                item.Text = Convert.ToString(j);
                YearEnums.Add(item);
            }

            return YearEnums;
        }

        private int yearMeans = int.Parse(ConfigurationManager.AppSettings["yearMeans"]);

        private static List<SelectListItem> GetListMonth()
        {
            DateTimeFormatInfo formatInfoinfo = new DateTimeFormatInfo();
            List<SelectListItem> monthEnums = new List<SelectListItem>();
            String[] months = formatInfoinfo.MonthNames;
            for (int j = 0; j < months.Length; j++)
            {
                var item = new SelectListItem();
                item.Value = Convert.ToString(j + 1);
                item.Text = months[j];
                monthEnums.Add(item);
            }
            return monthEnums;
        }

        private List<SelectListItem> GetListActivity()
        {
            List<SelectListItem> ActivityEnums = new List<SelectListItem>();
            List<Activity> listActivity = ActivityManager.GetAll();
            for (int i = 0; i < listActivity.Count(); i++)
            {
                var item = new SelectListItem();
                item.Value = Convert.ToString(listActivity[i].Id);
                item.Text = listActivity[i].Name;// First<string>();
                ActivityEnums.Add(item);
            }
            return ActivityEnums;
        }

        private Cram CreateCram(int month, int year)
        {
            Cram cram = new Cram();
            cram.UserId = ((SessionData)Session["MySessionData"]).CurrentUser.Id;
            cram.MonthId = month;
            cram.Year = year;
            CramManager.InsertCram(cram);
            return cram;
        }
         [AcceptVerbs(HttpVerbs.Post)]
         [Authorize]
        public ActionResult AddCramLine(String activityEnum)
        {
            Cram cram = (Cram)((SessionData)Session["MySessionData"]).CurrentCram;
            CramLine NewCramLine = CreateCramLine(activityEnum, cram);

            return RedirectToAction("Edit", new { Id = NewCramLine.Id });
           
        }

         private CramLine CreateCramLine(String activityEnum, Cram cram)
         {
             CramLine NewCramLine = new CramLine(cram, ActivityManager.GetActivityById(new Guid(activityEnum)), String.Empty);
             NewCramLine.Id = Guid.NewGuid();
             NewCramLine.WorkingDays = String.Empty;
             cram.AddCramLine(NewCramLine);
            
             return NewCramLine;
         }

        [Authorize]
        public ActionResult Edit(Guid id)
        {
            Cram cram = (Cram)((SessionData)Session["MySessionData"]).CurrentCram;
            PageData mod = new PageData()
            {
                Cram = cram,
                GridViewData = new GridViewData<CramLine>
                {
                    PagedList = cram.CramLines.ToList().ToPagedList<CramLine>(),
                    EditItem = cram.CramLines.Where(e => e.Id == id).FirstOrDefault<CramLine>()
                }

            };

            ViewData["activityEnum"] = GetListActivity();
            ViewData["monthEnum"] = GetListMonth();
            ViewData["yearEnum"] = GetYearList();
            return View("CramDetails", mod);
        }

        [Authorize]
        public ActionResult UpdateCramLine(Guid id, FormCollection formCollection)
         {
             Cram cram  = ((SessionData)Session["MySessionData"]).CurrentCram;
             DateTime cramDate = new DateTime(cram.Year, cram.MonthId, 1);
             List<bool> workingDays = WorkingDay.MonthWorkingDays(cramDate);
             Guid activityId = new Guid(formCollection["ActivityId"]);
   
             //rates : sum o row rate
             string rates = "";
             string IdCell = string.Empty;
             for (int i = 0; i < workingDays.Count; i++)
             {
                 if (workingDays[i])
                 {
                     IdCell = "rateCel" + i + "_" + id;
                     rates = rates + formCollection[IdCell];
                 }
                 else
                 {
                     rates = rates + "0";
                 }
                 if (i < workingDays.Count - 1)
                     rates = rates + ";";
             }

             CramLine CramLineToSave = cram.CramLines.Where(c => c.Id == id).FirstOrDefault<CramLine>();

             CramLineToSave.WorkingDays = rates;
             CramLineToSave.ActivityId = activityId;
             CramLineToSave.Description = formCollection["Description" + id.ToString()];


             CramLineToSave.Activity = ActivityManager.GetActivityById(activityId);

             return CramDetails();
         }

        [Authorize]
        public ActionResult CramDetails()
        {
            Cram cram = ((SessionData)Session["MySessionData"]).CurrentCram;
            PageData mod = new PageData()
            {
                Cram = cram,
                GridViewData = new GridViewData<CramLine>
                {
                    PagedList = cram.CramLines.ToList().ToPagedList<CramLine>(),

                }
            };
             
            ViewData["activityEnum"] = GetListActivity();
            ViewData["monthEnum"] = GetListMonth();
            ViewData["yearEnum"] = GetYearList();
            return View("CramDetails", mod);
        }


        /// <summary>
        /// Get method to delete a CRAM.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
       [Authorize]
        public ActionResult Delete(Guid id)
        {
             Cram cram = ((SessionData)Session["MySessionData"]).CurrentCram;
             CramLine CramLineToDelete = cram.CramLines.Where(c => c.Id == id).FirstOrDefault<CramLine>();
            //((SessionData)Session["MySessionData"]).CurrentCram.CramLines.Remove(tmp);
            cram.DeleteCramLine(CramLineToDelete);

            return  CramDetails();
        }

       [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult SaveCram(String commentary) 
        {
            Cram cram = ((SessionData)Session["MySessionData"]).CurrentCram;
            cram.Comment = commentary;
            cram.LastModificationDate = DateTime.Now;
            CramManager.SaveOrUpDateCram(cram);

            return CramDetails();
        }

    }
}
